package com.flk.oauth.config;

import com.flk.oauth.security.SecurityConstants;
import com.flk.oauth.sms.config.SmsConfig;
import com.flk.oauth.vaildatecode.config.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

import javax.servlet.http.HttpServletResponse;

/**
 * @author xxwy
 * on 2018/10/15 0015
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    ValidateCodeSecurityConfig validateCodeSecurityConfig;
    @Autowired
    SmsConfig smsConfig;
    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .apply(validateCodeSecurityConfig).and()
                .apply(smsConfig).and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setHeader("Content-type", "application/json;charset=utf-8");
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Allow-Credentials", "true");
                    response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");
                    response.setHeader("Access-Control-Allow-Methods", "PUT,GET,POST,DELETE,OPTIONS");
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
                })
                .and()
                .authorizeRequests()
                .antMatchers("/code/*",
                        SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE_IMAGE,
                        SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE,
                        "/anonymity/*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler);
    }
}
